package org.swift.mashup.engine.concurrency.agenda;

import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.apache.axis2.context.MessageContext;
import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.swift.mashup.engine.model.ActionOutput;
import org.swift.mashup.engine.model.Grab;

public class AgendaLogger implements AgendaListener {
	private static Log log = LogFactory.getLog(AgendaLogger.class);
	private final static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd' 'HH:mm:ss.SSS");

	@SuppressWarnings("rawtypes")
	@Override
	public void handleEvent(AgendaEvent event) {
		try{
			AgendaItem item = event.getItem();
			switch (event.getType()) {
				case AgendaActionItemCompleted:
					Action action = ((Action) item.getItem());
					if(action instanceof Grab){
						HttpServletRequest req = (HttpServletRequest)((MessageContext)item.getContext()).getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
						String queryString = req.getQueryString();
						if(queryString.equals(null)){
							queryString = "";
						}
					    ActionOutput actionOutput = action.getActionResult();
						Map<String,Collection> resultMap = new HashMap<String,Collection>();
						actionOutput.updateOutputMap(resultMap, item.getReturnType());
						for (Entry<String,Collection> entry : resultMap.entrySet()){
							log.info(
								dateFormat.format(new java.util.Date()) + "," +
								req.getRequestURL().toString() + "," +
								queryString + "," +
								((Grab)action).getMashupName() + "," +
								action.getName() + "," +
								entry.getKey() + "," +
								item.getDuration() + ","
							);
						}
					}
					break;
			}
		}catch(Exception e){
			//do nothing - keep stack trace out of logs
		}
	}
	
	public static boolean isEnabled(){
		return log.isInfoEnabled();
	}

}
